<template>
  <div class="imageChecker">
    <input
      v-show="false"
      ref="fileCheck"
      type="file"
      accept="image/*"
      @change="fileChange"
    />
    <div class="checker">
      <el-image
        v-if="src"
        style="width: 120px; height: 120px"
        :src="src"
        fit="contain"
      />
      <div v-else class="selecter" @click="handleSelect">
        <i class="el-icon-plus" />
      </div>
      <div v-if="src" class="tools">
        <i class="el-icon-edit" @click.stop="handleSelect" />
        <i class="el-icon-zoom-in" @click.stop="preview" />
      </div>
    </div>
    <el-image v-show="false" ref="test" :src="src" :preview-src-list="[src]" />
  </div>
</template>

<script>
export default {
  props: {
    imageUrl: {
      default: '',
      type: String
    }
  },
  data() {
    return {
      src: this.imageUrl,
      file: ''
    }
  },
  methods: {
    handleSelect() {
      const vm = this
      vm.$refs.fileCheck.click()
    },
    fileChange(e) {
      const vm = this
      var files = e.target.files[0]
      if (!files) return
      vm.file = files
      vm.$emit('change', vm.file)
      if (!e || !window.FileReader) return // 判断是否支持FileReader
      const reader = new FileReader()
      reader.readAsDataURL(files) // 文件转换
      reader.onloadend = function () {
        vm.src = this.result
      }
    },
    preview() {
      const vm = this
      vm.$refs.test.clickHandler()
    }
  }
}
</script>

<style lang="scss" scoped>
.imageChecker {
  .checker {
    width: 120px;
    height: 120px;
    background-color: #fbfdff;
    border: 1px dashed #c0ccda;
    border-radius: 5px;
    position: relative;
    .selecter {
      width: 100%;
      height: 100%;
      display: flex;
      justify-content: center;
      align-items: center;
      cursor: pointer;
    }
    .el-icon-plus {
      font-size: 28px;
    }
    &:hover {
      border-color: #409eff;
      .tools {
        display: flex;
      }
    }
    .tools {
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      z-index: 5;
      font-size: 16px;
      color: #fff;
      display: flex;
      justify-content: center;
      align-items: center;
      display: none;
      background: rgba($color: #000000, $alpha: 0.4);
      i {
        cursor: pointer;
        &:hover {
          opacity: 0.6;
        }
        &:nth-of-type(1) {
          margin-right: 8px;
        }
      }
    }
  }
}
</style>
